"""Script to generate Markdown documentation about trees defined on pipeline data."""
import argparse
import glob
import logging
from pathlib import Path
import typing

from cki_lib import config_tree
from cki_lib import logger
from cki_lib import misc
from cki_lib import session
from cki_lib import yaml
import sentry_sdk

LOGGER: logging.Logger = logger.get_logger('cki_tools.pipeline_data_gen_tree_doc')
SESSION = session.get_session('cki_tools.pipeline_data_gen_tree_doc', raise_for_status=True)


def gen_trees_doc(tree_file: str, outputfile: str) -> bool:
    """Generate documentation for the configured trees on given file."""
    basename = Path(tree_file).stem
    content = f"# {basename} trees\n"
    LOGGER.info("processing content of %s", tree_file)
    data = config_tree.process_config_tree(yaml.load(file_path=tree_file, resolve_references=True))
    content = []
    content.append("---")
    content.append(f"title: Onboarded {basename} trees")
    content.append("---")
    found_tree = False
    for tree in sorted(data):
        # ignore if configuration is not for any git repository
        if 'git_url' not in data[tree]:
            continue
        responsible = None
        onboard_req = data[tree].get('onboard_request', 'N/A')
        description = data[tree].get('description', f"Run tests on {tree} kernel tree.")

        for report in data[tree]['.report_rules']:
            if report['send_to'] == 'failed_tests_maintainers':
                continue
            if isinstance(report['send_to'], list):
                responsible = list(map(lambda a: "<" + a + ">", report['send_to']))
                responsible = ", ".join(responsible)
            else:
                responsible = f"<{report['send_to']}>"
            break
        branches = ", ".join(data[tree][".branches"])
        dw_link = f"https://datawarehouse.cki-project.org/kcidb/checkouts?filter_gittrees={tree}"
        content.append(f'\n## [{tree}]({dw_link})\n')
        content.append(f'{description}\n')
        content.append(f'- repo: <{data[tree]["git_url"]}>')
        content.append(f'- branches: {branches}')
        if responsible:
            content.append(f'- responsible: {responsible}')
        content.append(f'- onboarding request: <{onboard_req}>')
        if responsible:
            content.append('- notifications: test maintainer and reponsible contact (see above)')
        else:
            content.append('- notifications: test maintainer')
        content.append(f'- test set: `{data[tree]["test_set"]}`')
        if 'tests_regex' in data[tree]:
            content.append(f'- tests regex: `{data[tree]["tests_regex"]}`')
        content.append(f'- architectures: `{data[tree]["architectures"]}`')
        # found information of at least 1 tree
        found_tree = True
    if found_tree:
        LOGGER.info("creating file %s", outputfile)
        with open(outputfile, 'w', encoding='utf-8') as file:
            file.write("\n".join(content))
            file.write("\n")
        LOGGER.debug("Generated content:")
        LOGGER.debug("\n".join(content))
    return found_tree


def main(argv: typing.Optional[typing.List[str]] = None) -> int:
    """Script to generate Markdown documentation about trees defined on pipeline data."""
    parser = argparse.ArgumentParser(
        description='Output the patch that would be needed to update y-stream trees in kpet-db')
    parser.add_argument('--pipeline-data', required=True,
                        help='Path to pipeline-data repo')
    args = parser.parse_args(argv)

    basepath = args.pipeline_data
    tree_files = glob.glob(f'{basepath}/*.yaml')

    for tree_file in sorted(tree_files):
        basename = Path(tree_file).stem
        outputfile = f'{basepath}/documentation/{basename}.md'
        gen_trees_doc(tree_file, outputfile)

    return 0


if __name__ == '__main__':
    misc.sentry_init(sentry_sdk)
    main()
